package com.example.tongyao.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.tongyao.common.SuperController;
import com.example.tongyao.system.entity.SysConfig;
import com.example.tongyao.system.entity.SysJob;
import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.system.entity.SysUserJob;
import com.example.tongyao.system.message.SystemMessage;
import com.example.tongyao.system.service.ISysJobService;
import com.example.tongyao.system.service.ISysUserJobService;
import com.example.tongyao.utils.DataResult;
import com.example.tongyao.utils.DateUtils;
import com.example.tongyao.utils.StringUtils;
import com.example.tongyao.utils.token.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 岗位表 前端控制器
 * </p>
 *
 * @author tongyao
 * @since 2021-09-05
 */
@RestController
@Api(tags = "系统_岗位前端控制器")
@RequestMapping("/system/sys-job")
public class SysJobController extends SuperController {

    @Resource
    private ISysJobService iSysJobService;

    @Resource
    private ISysUserJobService iSysUserJobService;

    /**
     * 分页查询所有岗位
     * @return
     */
    @ApiOperation(
            value = "查询岗位",
            notes = "分页查询所有岗位",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobName",value = "岗位名称"),
            @ApiImplicitParam(name = "pageNo",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数",defaultValue = "10"),
            @ApiImplicitParam(name = "sortBy",value = "排序字段（多个以英文逗号拼接）",defaultValue = "create_time"),
            @ApiImplicitParam(name = "order",value = "排序类型",defaultValue = "asc")
    })
    @GetMapping(value = "/jobPage" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult jobPage(
            @RequestParam(required = false) String jobName,
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "create_time") String sortBy,
            @RequestParam(defaultValue = "asc") String order) {

        LambdaQueryWrapper<SysJob> sysJobLambdaQueryWrapper = new LambdaQueryWrapper<>();

        if(StringUtils.isNotBlank(jobName)){
            sysJobLambdaQueryWrapper.like(SysJob::getJobName,jobName);
        }


        sysJobLambdaQueryWrapper.last(" order by "+sortBy+" "+order);

        Page<SysJob> page = new Page<>(pageNo,pageSize);
        IPage<SysJob> iPage = iSysJobService.page(page,sysJobLambdaQueryWrapper);
        return DataResult.setSuccess(iPage);
    }

    @ApiOperation(
            value = "增加岗位",
            notes = "增加一个岗位",
            httpMethod = "POST")
    @PostMapping(value = "/save" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult save(@Valid @RequestBody(required = true) SysJob sysJob) {

        codeExist(sysJob.getJobCode());

        SysUser user = (SysUser) UserUtils.getUserInfo();

        sysJob.setJobEnabled(true);
        sysJob.setDelFlag(1);
        sysJob.setCreateBy(user.getUserId());
        sysJob.setCreateTime(DateUtils.getDateTime());

        reuslt = iSysJobService.save(sysJob);
        if(!reuslt){
            throw new RuntimeException(SystemMessage.job+SystemMessage.add+SystemMessage.fail+SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "编辑岗位",
            notes = "编辑一个岗位，需根据jobId字段。",
            httpMethod = "PUT")
    @PutMapping(value = "/edit" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult edit(@Valid @RequestBody SysJob sysJob){

        SysUser user = (SysUser) UserUtils.getUserInfo();

        if(StringUtils.isBlank(sysJob.getJobId())){
            throw new RuntimeException("岗位编号不能为空！");
        }

        LambdaUpdateWrapper<SysJob> sysJobLambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        if(StringUtils.isNotBlank(sysJob.getJobName())){
            sysJobLambdaUpdateWrapper.set(SysJob::getJobName,sysJob.getJobName());
        }
        if(StringUtils.isNotBlank(sysJob.getJobCode())){
            codeExist(sysJob.getJobCode());
            sysJobLambdaUpdateWrapper.set(SysJob::getJobCode,sysJob.getJobCode());
        }
        if(StringUtils.isNotBlank(sysJob.getJobDesc())){
            sysJobLambdaUpdateWrapper.set(SysJob::getJobDesc,sysJob.getJobDesc());
        }
        if(StringUtils.isNotNull(sysJob.getSort())){
            sysJobLambdaUpdateWrapper.set(SysJob::getSort,sysJob.getSort());
        }

        sysJobLambdaUpdateWrapper.set(SysJob::getModifyBy,user.getUserId());
        sysJobLambdaUpdateWrapper.set(SysJob::getModifyTime,DateUtils.getDateTime());

        sysJobLambdaUpdateWrapper.eq(SysJob::getJobId,sysJob.getJobId());

        reuslt = iSysJobService.update(sysJobLambdaUpdateWrapper);
        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.job+
                            SystemMessage.update+
                            SystemMessage.fail+
                            SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "删除岗位",
            notes = "删除一个或多个岗位",
            httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobId",value = "岗位编号，多个以英文逗号拼接",required = true),
    })
    @DeleteMapping(value = "/delete" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult delete(@RequestParam String jobId){

        //从配置里获取默认岗位
        SysConfig sysConfig = iSysConfigService.getConfigByKey("sys_default_job");
        if(StringUtils.isNull(sysConfig)){
            throw new RuntimeException("系统配置：${sys_default_job} 为空！");
        }

        map = commonService.getOne(
                "job_id",
                "sys_job",
                "job_code = '"+sysConfig.getConfigValue()+"' and del_flag = 1"
        );
        if(StringUtils.isNull(map)){
            throw new RuntimeException("属性值为：${"+sysConfig.getConfigValue()+"} 查询出来的数据为空！");
        }

        String mapJobId = map.get("job_id").toString();
        if(mapJobId.equals(jobId)){
            throw new RuntimeException("经系统设置，该岗位不能删除！");
        }


        List jobIds = Arrays.asList(jobId.split(","));
        for (Object job: jobIds) {

            //校验是否删除默认岗位
            if(!mapJobId.equals(job)){

                //删除岗位
                LambdaUpdateWrapper<SysJob> sysJobLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                sysJobLambdaUpdateWrapper
                        .set(SysJob::getDelFlag,"0")
                        .eq(SysJob::getJobId,job);
                reuslt = iSysJobService.update(sysJobLambdaUpdateWrapper);
                if(!reuslt){
                    throw new RuntimeException(
                            SystemMessage.job+
                                    SystemMessage.delete+
                                    SystemMessage.fail+
                                    SystemMessage.a
                    );
                }

                //把用户岗位关系岗位字段替换成默认的
                LambdaUpdateWrapper<SysUserJob> sysUserJobLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                sysUserJobLambdaUpdateWrapper
                        .set(SysUserJob::getJobId,mapJobId)
                        .eq(SysUserJob::getJobId,job);
                reuslt = iSysUserJobService.update(sysUserJobLambdaUpdateWrapper);
                if(!reuslt){
                    throw new RuntimeException(
                            SystemMessage.user+
                                    SystemMessage.job+
                                    SystemMessage.relation+
                                    SystemMessage.update+
                                    SystemMessage.fail+
                                    SystemMessage.a
                    );
                }
            }



        }


        //注：把所有字符返回尽量使用SystemMessage代替

        //最后检查：
        //登录
        //删除的不能登录
        //禁用的不能登录
        //无角色不能登录
        //无部门不能登录
        //无岗位不能登录
        //角色、部门、岗位、菜单、用户、字典、系统配置、免认证路径、菜单路径、已删除的不能查询

        //后期考虑，添加：特殊字段判断是否能删除（系统字段）
        //后期考虑，部门、角色、菜单名称编码
        //后期考虑，字典添加业务类型字段

        //配置token可加密不加密
        //配置密码是否能加密


        //考虑 岗位和其他控制层里的code字段，实体中校验是否需要？



        //查询数据权限：
        // 每条数据新增时插入当前用户id
        // 根据当前部门id，查询所有用户的id
        //拿到当前所有用户的id，in 遍虑所有数据（想办法优化使用简单）



        //排序字段，做成为空则为1
        //所有描述必填
        //添加时，不穿编号则生成，传编号则用传的编号


        //修改所有编辑接口的里面多重if改为单个if

        return DataResult.setSuccess(null);
    }


    @ApiOperation(
            value = "更改状态",
            notes = "更改岗位的启用禁用状态",
            httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobId",value = "岗位编号",required = true),
            @ApiImplicitParam(name = "state",value = "岗位状态（true为启用，false为禁用）",required = true)
    })
    @PutMapping(value = "/changeState" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult changeState(
            @RequestParam String jobId,
            @RequestParam boolean state
    ){

        LambdaUpdateWrapper<SysJob> sysJobLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        sysJobLambdaUpdateWrapper
                .set(SysJob::isJobEnabled,state)
                .eq(SysJob::getJobId,jobId);
        reuslt = iSysJobService.update(sysJobLambdaUpdateWrapper);

        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.job +
                            SystemMessage.state+
                            SystemMessage.update +
                            SystemMessage.fail +
                            SystemMessage.a
            );
        }

        return DataResult.setSuccess(null);
    }


    /**
     * 判断岗位编码是否存在
     * @param code
     * @return
     */
    public void codeExist(String code){
        int count = commonService.getCount("sys_job","job_code = '"+code+"' and del_flag = 1");
        if(count > 0){
            throw new RuntimeException(code+" 岗位编码已存在！");
        }
    }
}
